﻿using System;
using System.Web.UI;
using BugTacker.Common;
using BugTracker.BusinessEntities.Entities.Company;
using BugTracker.BusinessLogic.Company;
using BugTracker.Core.Infrastructure.Exceptions;
using BugTracker.WebUX.Admin.Modules.AppCode;
using BugTracker.WebUX.WebCode;
using Microsoft.Practices.Unity;

namespace BugTracker.WebUX.Admin.Modules.Company
{
    public partial class UCCompanyDetail : BTUserControlBase
    {

        #region page load

        protected void Page_Load(object sender, EventArgs e)
        {
            ActionInfoBox.Text = "Ready";
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.green;
            InitButtonPanel();
            if (!Page.IsPostBack)
            {
                BindDropDown();
                ValidateUrlParam();
            }
        }

        #endregion

        #region bind dropdown

        private void BindDropDown()
        {
            var model = Global.IoC.Container.Resolve<ICompanyTypeService>().Load();
            this.CompanyTypeDropDown.DataSource = model;
            this.CompanyTypeDropDown.DataBind();
        }

        #endregion

        #region check url param

        private void ValidateUrlParam()
        {
            string param = Request.QueryString[BTHttpApplication.UrlParam.IMAGE_ID];
            if (!string.IsNullOrEmpty(param))
            {
                int id = 0;
                Int32.TryParse(param, out id);
                if (id != 0)
                {
                    this.Key = id;
                    BindData(id);
                }
            }
            else
            {
                SetInfoBoxAdding();
            }
        }

        #endregion

        #region bind data

        private void BindData(int id)
        {
            try
            {
                var model = Global.IoC.Container.Resolve<ICompanyService>().LoadById(id);
                if (model != null)
                {
                    this.Entity = model;
                    this.NameTextBox.Text = CommonRoutines.Decode(model.Name);
                    this.DescriptionTextBox.Text = CommonRoutines.Decode(model.Description);
                    CommonRoutines.DropDownSelectByValue(this.CompanyTypeDropDown, model.CompanyTypeID);
                    this.AddressTextBox.Text = CommonRoutines.Decode(model.Address);
                    this.PhoneTextBox.Text = CommonRoutines.Decode(model.Phone);
                    this.IsActiveCheckBox.Checked = model.IsActive;
                    this.SetInfoBoxUpdating();
                }
            }
            catch (BugTrackerExpection e)
            {
                SetInfoBoxError(e.Message);
            }
        }

        #endregion

        #region button panel

        private void InitButtonPanel()
        {
            ButtonPanel.PrepareResources();
            ButtonPanel.Submit.Visible = true;
            ButtonPanel.Return.Visible = true;
            ButtonPanel.Submit.Click += SubmitButton_Click;
            ButtonPanel.Return.Click += ReturnButton_Click; 
        }

        #endregion

        #region infobox

        private void SetInfoBoxAdding()
        {
            MessageInfoBox.Visible = true;
            MessageInfoBox.Text = Resources.Phrases.AddingRecord;
            MessageInfoBox.MessageType = InfoBox.InfoBox.MsgType.blue;
            ButtonPanel.Submit.Text = Resources.Controls.ButtonText_Save;
        }

        private void SetInfoBoxUpdating()
        {
            MessageInfoBox.Visible = true;
            MessageInfoBox.Text = Resources.Phrases.EditingRecord;
            MessageInfoBox.MessageType = InfoBox.InfoBox.MsgType.blue;
            ButtonPanel.Submit.Text = Resources.Controls.ButtonText_Update;
        }

        private void SetInfoBoxError(string message)
        {
            ActionInfoBox.Visible = true;
            ActionInfoBox.Text = message;
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.red;
        }

        #endregion

        #region saveadding

        private void SaveAdding()
        {
            var model = new BugTracker.BusinessEntities.Entities.Company.Company();
            var guid = Guid.NewGuid();
            model.CompanyTypeID = 0;
            model.Name = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.NameTextBox.Text, 50));
            model.Description = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.DescriptionTextBox.Text, 255));
            model.CompanyTypeID = Convert.ToInt32(this.CompanyTypeDropDown.SelectedValue);
            model.Address = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.AddressTextBox.Text, 255));
            model.Phone = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.PhoneTextBox.Text, 50));
            model.IsActive = this.IsActiveCheckBox.Checked;
            model.IsDeleted = false;
            model.RowGuid = guid;
            model.CreatedOn = DateTime.UtcNow;
            model.ModifiedOn = DateTime.UtcNow;

            try
            {
                Global.IoC.Container.Resolve<ICompanyService>().InsertObject(model);
                this.Entity = Global.IoC.Container.Resolve<ICompanyService>().LoadByGuid(guid);

                ActionInfoBox.Text = Resources.Phrases.InsertSuccessful;
                SetInfoBoxUpdating();

            }
            catch (BugTrackerExpection e)
            {
                SetInfoBoxError(e.Message);
            }
        }

        #endregion

        #region save editing

        private void SaveEditing()
        {
            var model = (BugTracker.BusinessEntities.Entities.Company.Company)this.Entity;
            model.Name = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.NameTextBox.Text, 50));
            model.Description = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.DescriptionTextBox.Text, 255));
            model.CompanyTypeID = Convert.ToInt32(this.CompanyTypeDropDown.SelectedValue);
            model.Address = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.AddressTextBox.Text, 255));
            model.Phone = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.PhoneTextBox.Text, 50));
            model.IsActive = this.IsActiveCheckBox.Checked;
            model.IsDeleted = false;
            model.ModifiedOn = DateTime.UtcNow;

            try
            {
                Global.IoC.Container.Resolve<ICompanyService>().UpdateObject(model);
                this.Entity = Global.IoC.Container.Resolve<ICompanyService>().LoadByGuid(model.RowGuid);

                ActionInfoBox.Text = Resources.Phrases.UpdateSuccessful;
                SetInfoBoxUpdating();
            }
            catch (BugTrackerExpection e)
            {
                SetInfoBoxError(e.Message);
            }
        }

        #endregion

        #region save

        private void Save()
        {
            if (Page.IsValid)
            {
                if (this.Entity == null)
                {
                    SaveAdding();
                }
                else
                {
                    SaveEditing();
                }
            }
        }

        #endregion

        #region button events

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            Save();
        }

        protected void ReturnButton_Click(object sender, EventArgs e)
        {
            Response.Redirect(BTHttpApplication.AppPaths.CompanyList);
        }

        #endregion

    }
}